package com.fj.netty.rpc.server.service;

import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public class ServiceFactory {
    private static final ConcurrentHashMap<String,String> serviceMap = new ConcurrentHashMap<>();
    private static final Properties properties = new Properties();
    static {
        InputStream resourceAsStream = ServiceFactory.class.getResourceAsStream("/application.properties");
        try {
            properties.load(resourceAsStream);
            for ( String name : properties.stringPropertyNames()) {
                if (name.endsWith("Service")) {
                    String instanceName = properties.getProperty(name);
                    serviceMap.put(name,instanceName);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Class<?> getService(String interfaceName){
        try {
            Class<?> aClass = Class.forName(interfaceName);
            if (aClass.isInterface()) {
                //查找实现类
                return Class.forName(serviceMap.get(interfaceName));
            }else{
                return aClass;
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
